package com.irdstudio.apicenter.gateway.comm;
/**
 * @docRoot
 * 变量解释,负责将其中的变量解释出来
 * @author guangming.li
 * @version 1.0
 * @date 2015-08-05
 */
import java.util.ArrayList;
import java.util.List;

public class MaccsVarParserUtil {
	
	/* 标准变量起始标识符 */
	private final static char NORMAL_VARIABLE_BEGIN = '[';
	/* 标签变量结束标识符 */
	private final static char NORMAL_VARIABLE_END = ']';
	
	
	/**
	 * 将字符串的变量解释出来
	 * @param vv
	 * @return
	 */
	public final static String parseString(String str, MaccsPacket vv) {

		int normalIndex = -1;
		List<String> normalVariable = new ArrayList<String>();
		StringBuffer sb = new StringBuffer(str);

		for (int i = 0; i < sb.length(); i++) {
			switch (sb.charAt(i)) {
			case NORMAL_VARIABLE_BEGIN:
				normalIndex = i + 1;
				break;
			case NORMAL_VARIABLE_END:
				if (normalIndex > -1)
					normalVariable.add(sb.substring(normalIndex, i));
				normalIndex = -1;
				break;
			}
		}
		
		//解释标准变量
		for (int i = 0; i < normalVariable.size(); i++) {
			String value = vv.getValue(normalVariable.get(i));
			StringBuffer varName = new StringBuffer();
			varName.append('\\');
			varName.append(NORMAL_VARIABLE_BEGIN);
			varName.append(normalVariable.get(i));
			varName.append('\\');
			varName.append(NORMAL_VARIABLE_END);
			str = str.replaceAll(varName.toString(), value);
		}
		
		return str;
	}
}
